C語言完整程式碼
#include <stdio.h> int main() { float height, weight, BMI; int statusValid; while (1) { printf("請輸入身高(cm): "); statusValid = scanf("%f", &height); printf("請輸入體重(公斤): "); statusValid &= scanf("%f", &weight); if (statusValid != 1 || height <= 0 || weight <= 0) { printf("您輸入的身高或體重不正確\n"); while(getchar() != '\n'); // 清空輸入緩衝區 continue; } BMI = weight / ((height / 100) * (height / 100)); char *status; if (BMI < 18.5) status = "過輕"; else if (BMI < 24) status = "正常"; else if (BMI < 27) status = "過重"; else if (BMI < 30) status = "輕度肥胖"; else if (BMI < 35) status = "中度肥胖"; else status = "重度肥胖"; printf("您的 BMI 為 %.0f, 屬於 %s\n", BMI, status); break; } return 0; }
輸出結果
也可以使用Python的 try except else
function 改寫
Python完整程式碼
while True: try: height = float(input("請輸入身高(公分): ")) weight = float(input("請輸入體重(公斤): ")) except ValueError: print("這不是有效的數字") continue if height <= 0 or weight <= 0: print("您輸入的身高或體重不正確") else: BMI = weight / ((height / 100) ** 2) rounded_BMI = round(BMI, 0) if BMI < 18.5: status = "過輕" elif 18.5 <= BMI < 24: status = "正常" elif 24 <= BMI < 27: status = "過重" elif 27 <= BMI < 30: status = "輕度肥胖" elif 30 <= BMI < 35: status = "中度肥胖" else: status = "重度肥胖" print(f"您的BMI:{rounded_BMI}") print(f"您的BMI:{status}") break